package com.recource.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.recource.annonation.Login;
import com.recource.domain.*;
import com.recource.ro.UserRO;
import com.recource.type.jiuyeType;
import com.recource.util.HostHolder;
import com.recource.util.Result;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.recource.dao.*;
import com.recource.ro.PageRO;
import com.recource.vo.UserVO;
import net.sf.jsqlparser.Model;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@Controller
@RequestMapping("/admin")
@Transactional(rollbackFor = Exception.class)
@Login
public class AdminController {

    @Autowired
    private UserDao userDao;

    @Autowired
    private FileDao fileDao;

    @Value("${file.root}")
    private String root;

    @Value("${system.previewUrl}")
    private String url;


    @RequestMapping("/index")
    public String index(){
        return "/admin/index";
    }

    @RequestMapping("/user/add.html")
    public ModelAndView addHtml(){
        ModelAndView modelAndView = new ModelAndView();
        List<Major> majors = majorDao.selectList(null);
        List<Grade> grades = gradeDao.selectList(null);
        List<Bj> bjs = bjDao.selectList(null);
        modelAndView.addObject("majors", majors);
        modelAndView.addObject("grades", grades);
        modelAndView.addObject("bjs", bjs);
        modelAndView.setViewName("/admin/user/detail");
        return modelAndView;
    }

    @RequestMapping("/user/page")
    public ModelAndView list(PageRO<User> ro){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("/admin/user/list");

        User loginUser = hostHolder.getUser();

        if(Objects.equals(loginUser.getUserType(), 1)){
            if(StringUtils.isEmpty(loginUser.getMid()) || StringUtils.isEmpty(loginUser.getGid()) || StringUtils.isEmpty(loginUser.getBjId())){
                Page<User> userPage = new Page<>();
                modelAndView.addObject("number", 0);


                modelAndView.addObject("page", userPage);
                return modelAndView;
            }
        }


        LambdaQueryWrapper<Grade> gradeLambdaQueryWrapper = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<Major> majorLambdaQueryWrapper = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<Bj> bjLambdaQueryWrapper = new LambdaQueryWrapper<>();

        Page<User> userPageRO = userDao.selectCustomPageByGradeAndMajorAndBj(ro, loginUser);
        userPageRO.getRecords().forEach(user -> {
            LambdaQueryWrapper<Grade> eq = gradeLambdaQueryWrapper.eq(Grade::getId, user.getGid());
            Grade grade = gradeDao.selectOne(eq);
            user.setGrade(grade);

            LambdaQueryWrapper<Major> eq1 = majorLambdaQueryWrapper.eq(Major::getId, user.getMid());
            Major major = majorDao.selectOne(eq1);
            user.setMajor(major);

            LambdaQueryWrapper<Bj> eq2 = bjLambdaQueryWrapper.eq(Bj::getId, user.getBjId());
            Bj bj = bjDao.selectOne(eq2);
            user.setBj(bj);
        });

        BigDecimal divide = new BigDecimal(0);

        if(!CollectionUtils.isEmpty(userPageRO.getRecords())){
            LambdaQueryWrapper<jiuye> jiuyeLambdaQueryWrapper = new LambdaQueryWrapper<>();
            jiuyeLambdaQueryWrapper.orderByDesc(jiuye::getDate);
            jiuyeLambdaQueryWrapper.eq(jiuye::getType, 1);
            jiuyeLambdaQueryWrapper.in(jiuye::getUid, userPageRO.getRecords().stream().map(User::getId).collect(Collectors.toList()));
            List<jiuye> jiuyes = jiuyeDao.selectList(jiuyeLambdaQueryWrapper);
            Map<Integer, BigDecimal> collect = jiuyes.stream().collect(Collectors.groupingBy(jiuye::getUid, Collectors.collectingAndThen(Collectors.toList(), list -> {
                if (!CollectionUtils.isEmpty(list)) {
                    return list.get(0).getSalary();
                }
                return new BigDecimal(0);
            })));
            BigDecimal total = collect.values().stream().filter(Objects::nonNull).reduce(new BigDecimal("0"), BigDecimal::add);
            divide = total.divide(new BigDecimal(userPageRO.getTotal()));
        }
        modelAndView.addObject("number", divide);


        modelAndView.addObject("page", userPageRO);
        return modelAndView;
    }

    @RequestMapping("/user/detail")

    public ModelAndView detail(String id){
        ModelAndView modelAndView = new ModelAndView();
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getId, id);
        User user = userDao.selectOne(wrapper);
        if(user == null){
            throw new RuntimeException("用户不存在");
        }
        List<Major> majors = majorDao.selectList(null);
        List<Grade> grades = gradeDao.selectList(null);
        List<Bj> bjs = bjDao.selectList(null);
        modelAndView.addObject("majors", majors);
        modelAndView.addObject("grades", grades);
        modelAndView.addObject("bjs", bjs);
        modelAndView.setViewName("/admin/user/detail");
        modelAndView.addObject("user", user);
        return modelAndView;
    }

    @RequestMapping("/user/update")
    public ModelAndView update(UserRO ro){
        ModelAndView modelAndView = new ModelAndView();
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        if(Objects.nonNull(ro.getId())){
            wrapper.eq(User::getId, ro.getId());
            User user = userDao.selectOne(wrapper);
            if(user == null){
                throw new RuntimeException("用户不存在");
            }
            user.setUsername(ro.getUsername());
            user.setUserType(ro.getUserType());
            user.setPhone(ro.getPhone());
            user.setMid(ro.getMid());
            user.setGid(ro.getGid());
            user.setBjId(ro.getBjId());

            userDao.updateById(user);
        }else{
            wrapper.eq(User::getUsername, ro.getUsername());
            User user = userDao.selectOne(wrapper);
            if(user != null){
                throw new RuntimeException("用户名已经存在了");
            }
            User user1 = new User();
            String salt = UUID.randomUUID().toString().substring(0, 5);
            user1.setSalt(salt);
            StringBuilder sb = new StringBuilder();
            try {
                String password = DigestUtils.md5DigestAsHex((sb.append(salt).append(ro.getPassword())).toString().getBytes());
                user1.setPassword(password);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            user1.setPhone(ro.getPhone());
            user1.setUserType(ro.getUserType());
            user1.setUsername(ro.getUsername());
            user1.setMid(ro.getMid());
            user1.setGid(ro.getGid());
            user1.setBjId(ro.getBjId());
            userDao.insert(user1);
        }
        modelAndView.setViewName("redirect:/admin/user/page");
        return modelAndView;
    }

    @RequestMapping("/user/delete")
    public ModelAndView update(int id){
        ModelAndView modelAndView = new ModelAndView();
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getId, id);
        User user = userDao.selectOne(wrapper);
        if(user == null){
            throw new RuntimeException("用户不存在");
        }
        userDao.deleteById(user);
        modelAndView.setViewName("redirect:/admin/user/page");
        return modelAndView;
    }


    @Autowired
    private JiuyeDao jiuyeDao;

    @Autowired
    private HostHolder hostHolder;

    @Autowired
    private ZhiyeDao zhiyeDao;

    /**
     * 获取就业信息
     * @return
     */
    @RequestMapping("/user/getjiutemessage")
    @ResponseBody
    public ResponseEntity<Result<UserVO>> getjiutemessage(int type, Integer uid){
        User loginUser = hostHolder.getUser();
        LambdaQueryWrapper<jiuye> a = new LambdaQueryWrapper<>();
        if(Objects.equals(loginUser.getUserType(), 1)){
            a.eq(jiuye::getFlag, 0);
        }
        a.eq(jiuye::getUid, uid);
        a.eq(jiuye::getType, type);
        List<jiuye> jiuyes = jiuyeDao.selectList(a);
        UserVO vo = new UserVO();
        LambdaQueryWrapper<User> b = new LambdaQueryWrapper<>();
        b.eq(User::getId, uid);
        User user = userDao.selectOne(b);
        vo.setUser(user);
        vo.setJiuyeList(jiuyes);
        vo.setType(type);
        Result<UserVO> userVOResult = new Result<>(vo);
        return new ResponseEntity<>(userVOResult, HttpStatus.OK);
    }

    @RequestMapping("/user/getzhiyemessage")
    @ResponseBody
    public ResponseEntity<Result<UserVO>> getzhiyemessage(Integer uid){
        User loginUser = hostHolder.getUser();
        LambdaQueryWrapper<User> b = new LambdaQueryWrapper<>();

        b.eq(User::getId, uid);
        User user = userDao.selectOne(b);
        LambdaQueryWrapper<zhiye> a = new LambdaQueryWrapper<>();
        if(Objects.equals(loginUser.getUserType(), 1)){
            a.eq(zhiye::getFlag, 0);
        }
        a.eq(zhiye::getUid, user.getId());
        List<zhiye> zhiyes = zhiyeDao.selectList(a);
        UserVO vo = new UserVO();
        vo.setUser(user);
        vo.setZhiyeList(zhiyes);
//        vo.setType(type);
        Result<UserVO> userVOResult = new Result<>(vo);
        return new ResponseEntity<>(userVOResult, HttpStatus.OK);
    }

    /**
     * 我的就业信息
     */
    @RequestMapping("/user/myjiuye")
    public ModelAndView myjiuye(){
        User user = hostHolder.getUser();
        LambdaQueryWrapper<jiuye> a = new LambdaQueryWrapper<>();
        a.eq(jiuye::getUid, user.getId());
        List<jiuye> jiuyes = jiuyeDao.selectList(a);

        ModelAndView mav = new ModelAndView();
        mav.setViewName("/admin/my/jiuye/list");
        mav.addObject("jiuyes", jiuyes);
        return mav;
    }

    @RequestMapping("/user/myjiuye/update")
    public ModelAndView myjiuyeupdate(jiuye jiuye){
        User user = hostHolder.getUser();
        if(StringUtils.isEmpty(jiuye.getId())){
            jiuye.setUid(user.getId());
            jiuyeDao.insert(jiuye);

            zhiye zy = new zhiye();
            BeanUtils.copyProperties(jiuye, zy);
            zy.setId(null);
            zy.setUid(user.getId());
            zy.setDate(new Date());
            zhiyeDao.insert(zy);
        }else{
            jiuyeDao.updateById(jiuye);
            zhiye zy = new zhiye();
            BeanUtils.copyProperties(jiuye, zy);
            zy.setId(null);
            zy.setUid(user.getId());
            zy.setDate(new Date());
            zhiyeDao.insert(zy);
        }
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("redirect:/admin/user/myjiuye");
        return modelAndView;
    }

    @RequestMapping("/user/myjiuye/detail")
    public ModelAndView myjiuyedetail(String id){
        User user = hostHolder.getUser();
        LambdaQueryWrapper<jiuye> a = new LambdaQueryWrapper<>();
        a.eq(jiuye::getId, id);
        jiuye jiuye = jiuyeDao.selectOne(a);
        ModelAndView m = new ModelAndView();
        m.addObject("jiuye", jiuye);
        m.setViewName("/admin/my/jiuye/detail");
        return m;
    }

    @RequestMapping("/user/myjiuye/add.html")
    public String jiuyemhad(){
        return "/admin/my/jiuye/detail";
    }

    @RequestMapping("/user/myzhiye")
    public ModelAndView myzhiye(){
        User user = hostHolder.getUser();
        LambdaQueryWrapper<zhiye> a = new LambdaQueryWrapper<>();
        a.eq(zhiye::getUid, user.getId());
        a.orderByDesc(zhiye::getDate);
        List<zhiye> zhiyes = zhiyeDao.selectList(a);

        ModelAndView mav = new ModelAndView();
        mav.setViewName("/admin/my/zhiye/list");
        mav.addObject("zhiyes", zhiyes);
        return mav;
    }

    @RequestMapping("/user/myzhiye/add.html")
    public String myzhiyeadd(){
        return "/admin/my/zhiye/detail";
    }

    @RequestMapping("/user/myzhiye/detail")
    public ModelAndView myzhiyedetail(String id){
        LambdaQueryWrapper<zhiye> a = new LambdaQueryWrapper<>();
        a.eq(zhiye::getId, id);
        zhiye zhiye = zhiyeDao.selectOne(a);
        ModelAndView mav = new ModelAndView();
        mav.addObject("zhiye", zhiye);
        mav.setViewName("/admin/my/zhiye/detail");
        return mav;
    }

    @RequestMapping("/user/myzhiye/update")
    public ModelAndView myzhiyeupdate(zhiye zy){
        User user = hostHolder.getUser();
        if(StringUtils.isEmpty(zy.getId())){
            zy.setUid(user.getId());
            zhiyeDao.insert(zy);
        }else{
            zhiyeDao.updateById(zy);
        }
        ModelAndView m = new ModelAndView();
        m.setViewName("redirect:/admin/user/myzhiye");
        return m;
    }


    @Autowired
    private DiaochaDao diaochaDao;

    @RequestMapping("/diaocha/add.html")
    public ModelAndView diaochaadd(){
        ModelAndView modelAndView = new ModelAndView();
        List<Major> majors = majorDao.selectList(null);
        List<Grade> grades = gradeDao.selectList(null);
        List<Bj> bjs = bjDao.selectList(null);
        modelAndView.addObject("majors", majors);
        modelAndView.addObject("grades", grades);
        modelAndView.addObject("bjs", bjs);
        modelAndView.setViewName("/admin/diaocha/detail");
        return modelAndView;
    }

    @RequestMapping("/diaocha/list")
    public ModelAndView diaochalist(){

        User loginUser = hostHolder.getUser();
        ModelAndView mav = new ModelAndView();
        LambdaQueryWrapper<diaocha> diaochaLambdaQueryWrapper = new LambdaQueryWrapper<>();
        if(Objects.equals(loginUser.getUserType(), 1)){
            diaochaLambdaQueryWrapper.eq(diaocha::getMid, loginUser.getMid());
            diaochaLambdaQueryWrapper.eq(diaocha::getGid, loginUser.getGid());
            diaochaLambdaQueryWrapper.eq(diaocha::getBjId, loginUser.getBjId());
        }
        List<diaocha> diaochas = diaochaDao.selectList(diaochaLambdaQueryWrapper);
        LambdaQueryWrapper<Grade> gradeLambdaQueryWrapper = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<Major> majorLambdaQueryWrapper = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<Bj> bjLambdaQueryWrapper = new LambdaQueryWrapper<>();
        diaochas.forEach(diaocha -> {
            LambdaQueryWrapper<Grade> eq = gradeLambdaQueryWrapper.eq(Grade::getId, diaocha.getGid());
            Grade grade = gradeDao.selectOne(eq);
            diaocha.setGrade(grade);

            LambdaQueryWrapper<Major> eq1 = majorLambdaQueryWrapper.eq(Major::getId, diaocha.getMid());
            Major major = majorDao.selectOne(eq1);
            diaocha.setMajor(major);

            LambdaQueryWrapper<Bj> eq2 = bjLambdaQueryWrapper.eq(Bj::getId, diaocha.getBjId());
            Bj bj = bjDao.selectOne(eq2);
            diaocha.setBj(bj);
        });
        mav.addObject("list", diaochas);
        mav.setViewName("/admin/diaocha/list");
        return mav;
    }

    @RequestMapping("/diaocha/update")
    public ModelAndView diaochaupdate(diaocha dc){
        ModelAndView mav = new ModelAndView();
        diaochaDao.insert(dc);
        mav.setViewName("redirect:/admin/diaocha/list");
        return mav;
    }

    @RequestMapping("/diaocha/detail")
    public ModelAndView diaochadetail(String id){
        LambdaQueryWrapper<diaocha> a = new LambdaQueryWrapper<>();
        a.eq(diaocha::getId, id);
        diaocha dc = diaochaDao.selectOne(a);
        ModelAndView mav = new ModelAndView();
        List<Major> majors = majorDao.selectList(null);
        List<Grade> grades = gradeDao.selectList(null);
        List<Bj> bjs = bjDao.selectList(null);
        mav.addObject("majors", majors);
        mav.addObject("grades", grades);
        mav.addObject("bjs", bjs);
        mav.addObject("diaocha", dc);
        mav.setViewName("/admin/diaocha/detail");
        return mav;
    }

    @RequestMapping("/diaocha/updatemessage")
    public ModelAndView updatemessage(String id){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("dcId", id);
        modelAndView.setViewName("/admin/my/jiuye/detail");
        return modelAndView;
    }


    @RequestMapping("/diaocha/select")
    public ModelAndView diaochaselect(){
        ModelAndView modelAndView = new ModelAndView();
        LambdaQueryWrapper<jiuye> jiuyeLambdaQueryWrapper = new LambdaQueryWrapper<>();
        jiuyeLambdaQueryWrapper.isNotNull(jiuye::getDcId);
        List<jiuye> jiuyes = jiuyeDao.selectList(jiuyeLambdaQueryWrapper);
        jiuyes.forEach(jiuye -> {
            LambdaQueryWrapper<diaocha> diaochaLambdaQueryWrapper = new LambdaQueryWrapper<>();
            diaochaLambdaQueryWrapper.eq(diaocha::getId, jiuye.getDcId());
            diaocha diaocha = diaochaDao.selectOne(diaochaLambdaQueryWrapper);
            jiuye.setDiaocha(diaocha);
        });
        modelAndView.addObject("jiuyes", jiuyes);
        modelAndView.setViewName("/admin/diaocha/listselect");
        return modelAndView;
    }



    @Autowired
    private GradeDao gradeDao;

    @Autowired
    private MajorDao majorDao;

    @Autowired
    private BjDao bjDao;

    @RequestMapping("/banji/add.html")
    public String banjiAdd(){
        return "/admin/banji/detail";
    }
    @RequestMapping("/banji/update")
    public ModelAndView banjiupdate(Bj bj){
        ModelAndView mav = new ModelAndView();
        if(Objects.nonNull(bj.getId())){
            LambdaQueryWrapper<Bj> bjLambdaQueryWrapper = new LambdaQueryWrapper<>();
            bjLambdaQueryWrapper.eq(Bj::getId, bj.getId());
            Bj bj1 = bjDao.selectOne(bjLambdaQueryWrapper);
            bj1.setName(bj.getName());
            bjDao.updateById(bj1);
        }else{

            bjDao.insert(bj);

        }

        mav.setViewName("redirect:/admin/banji/list");
        return mav;
    }

    @RequestMapping("/banji/detail")
    public ModelAndView banjidetail(String id){
        LambdaQueryWrapper<Bj> bjLambdaQueryWrapper = new LambdaQueryWrapper<>();
        bjLambdaQueryWrapper.eq(Bj::getId, id);
        Bj bj = bjDao.selectOne(bjLambdaQueryWrapper);
        ModelAndView mav = new ModelAndView();
        mav.addObject("bj", bj);
        mav.setViewName("/admin/banji/detail");
        return mav;
    }

    @RequestMapping("/banji/list")
    public ModelAndView banjilist(){
        ModelAndView mav = new ModelAndView();
        mav.addObject("list", bjDao.selectList(null));
        mav.setViewName("/admin/banji/list");
        return mav;
    }


    // ====== 专业

    @RequestMapping("/major/add.html")
    public String majoraddhtml(){
        return "/admin/major/detail";
    }
    @RequestMapping("/major/update")
    public ModelAndView majorupdate(Major major){
        ModelAndView mav = new ModelAndView();
        if(Objects.nonNull(major.getId())){
            LambdaQueryWrapper<Major> bjLambdaQueryWrapper = new LambdaQueryWrapper<>();
            bjLambdaQueryWrapper.eq(Major::getId,major.getId());
            Major major1 = majorDao.selectOne( bjLambdaQueryWrapper);
            major1.setName(major.getName());
            majorDao.updateById(major1);
        }else{

            majorDao.insert(major);

        }

        mav.setViewName("redirect:/admin/major/list");
        return mav;
    }

    @RequestMapping("/major/detail")
    public ModelAndView majordetail(String id){
        LambdaQueryWrapper<Major> bjLambdaQueryWrapper = new LambdaQueryWrapper<>();
        bjLambdaQueryWrapper.eq(Major::getId, id);
        Major major = majorDao.selectOne(bjLambdaQueryWrapper);
        ModelAndView mav = new ModelAndView();
        mav.addObject("major", major);
        mav.setViewName("/admin/major/detail");
        return mav;
    }

    @RequestMapping("/major/list")
    public ModelAndView marjorlist(){
        ModelAndView mav = new ModelAndView();
        mav.addObject("list", majorDao.selectList(null));
        mav.setViewName("/admin/major/list");
        return mav;
    }

    @RequestMapping("/grade/add.html")
    public String gradeaddhtml(){
        return "/admin/grade/detail";
    }
    @RequestMapping("/grade/update")
    public ModelAndView gradeupdate(Grade grade){
        ModelAndView mav = new ModelAndView();
        if(Objects.nonNull(grade.getId())){
            LambdaQueryWrapper<Grade> bjLambdaQueryWrapper = new LambdaQueryWrapper<>();
            bjLambdaQueryWrapper.eq(Grade::getId, grade.getId());
            Grade grade1 = gradeDao.selectOne(bjLambdaQueryWrapper);
            grade1.setName(grade.getName());
            gradeDao.updateById(grade1);
        }else{

            gradeDao.insert(grade);

        }

        mav.setViewName("redirect:/admin/grade/list");
        return mav;
    }

    @RequestMapping("/grade/detail")
    public ModelAndView gradedetail(String id){
        LambdaQueryWrapper<Grade> bjLambdaQueryWrapper = new LambdaQueryWrapper<>();
        bjLambdaQueryWrapper.eq(Grade::getId, id);
        Grade grade = gradeDao.selectOne(bjLambdaQueryWrapper);
        ModelAndView mav = new ModelAndView();
        mav.addObject("grade", grade);
        mav.setViewName("/admin/grade/detail");
        return mav;
    }

    @RequestMapping("/grade/list")
    public ModelAndView gradelist(){
        ModelAndView mav = new ModelAndView();
        mav.addObject("list", gradeDao.selectList(null));
        mav.setViewName("/admin/grade/list");
        return mav;
    }


}
